package com.example.demo.common.util;

import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

public class XWPFTableUtil {

    public  void mergeCells(XWPFTable table, int firstRow, int lastRow, int firstCol, int lastCol){
        for (int rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
            mergeCellsHorizontally(table, rowIndex, firstCol, lastCol);
        }
    }

    /**
     * @Description: 跨列合并
     */
    public void mergeCellsHorizontally(XWPFTable table, int row, int firstCol, int lastCol){
        XWPFTableCell cell;
        for (int cellIndex = firstCol; cellIndex <= lastCol; cellIndex++) {
            cell = table.getRow(row).getCell(cellIndex);
            if (cellIndex == firstCol) {
                getPrOfCell(cell).addNewHMerge().setVal(STMerge.RESTART);
            } else {
                getPrOfCell(cell).addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * @Description: 跨行合并
     */
    public void mergeCellsVertically(XWPFTable table, int col, int firstRow, int lastRow) {
        XWPFTableCell cell;
        for (int rowIndex = firstRow; rowIndex <= lastRow; rowIndex++) {
            cell = table.getRow(rowIndex).getCell(col);
            if (rowIndex == firstRow) {
                getPrOfCell(cell).addNewVMerge().setVal(STMerge.RESTART);
            } else {
                getPrOfCell(cell).addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    public CTTcPr getPrOfCell(XWPFTableCell cell){
        CTTc cttc = cell.getCTTc();
        CTTcPr tcPr = cttc.isSetTcPr() ? cttc.getTcPr() : cttc.addNewTcPr();
        return tcPr;
    }
}
